<template>
  <div class="address_manage">
    <div class="list" v-if="addressList.length">
      <van-swipe-cell v-for="item in addressList" :key="item.id" class="item">
        <div class="item-content" @click="itemClick(item)">
          <div class="left">
            <p class="name">{{ item.name }}</p>
            <p class="tag" v-if="item.is_default == 1">默认</p>
          </div>
          <div class="center">
            <p class="phone">{{ item.mobile }}</p>
            <p class="addr">{{ item.address }} {{ item.address_detail }}</p>
          </div>
          <img
            class="edit"
            src="../../assets/images/edit.png"
            alt=""
            @click.stop="editClick(item)"
          />
        </div>
        <template #right>
          <van-button
            square
            text="删除"
            type="danger"
            class="delete-button"
            @click="removeItem(item)"
          />
        </template>
      </van-swipe-cell>
    </div>
    <div class="empty" v-else>
      <van-empty description="暂无数据" />
    </div>
    <div class="footer">
      <van-button
        plain
        text="+ 新建地址"
        class="addBtn"
        color="#b4282b"
        @click="addClick"
      />
    </div>
  </div>
</template>
<script>
import { getListAction, deleteAction } from "@/api/addressmanage/index";
export default {
  data() {
    return {
      addressList: [],
    };
  },
  methods: {
    itemClick(item) {
      let from = this.$route.query.from;
      if (from == "orderconfirm") {
        localStorage.setItem("selAddressId", item.id);
        this.$router.go(-1);
      }
    },
    // 删除地址
    removeItem(item) {
      this.$dialog
        .confirm({
          title: "警告",
          message: "该操作会永久删除该数据,确定要删除吗?",
        })
        .then(async () => {
          const { data } = await deleteAction({
            id: item.id,
          });
          if (data) {
            // 删除成功后重新获取列表
            this.getAddressList();
            this.$toast("删除成功");
          } else {
            this.$toast("删除失败");
          }
        });
    },
    // 新增
    addClick() {
      this.$router.push({ path: "/addressmanage/editaddress" });
    },
    // 编辑点击
    editClick(item) {
      this.$router.push({
        path: "/addressmanage/editaddress",
        query: {
          id: item.id,
        },
      });
    },
    // 获取列表数据
    async getAddressList() {
      const { data } = await getListAction({
        openId: localStorage.getItem("openId"),
      });
      this.addressList = data;
    },
  },
  created() {
    this.getAddressList();
  },
};
</script>
<style lang="scss" scoped>
@import "./index.scss";
</style>
